package com.bilin.coin.network.callback;


import com.alibaba.android.arouter.launcher.ARouter;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.App;

import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;



/**
 *
 */

public abstract class CommonCallBack implements Observer<String> {


    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(String s) {
        try {
            //integer($int32)   状态码 {200：成功 | 401：未登录 | 403：账号冻结 | -1 条件未满足，错误信息msg }
            if (!s.equals("") && s != null) {
                if (s.contains("code")) {
                    JSONObject jsonObject = new JSONObject(s);
                    int code = jsonObject.getInt("code");
                    if (code == 200) {
                        onSuccess(jsonObject.optString("data"));
                        //onSuccess(s);
                    } else if (code == 401) {
                        onStopRefresh();
                        ARouter
                                .getInstance()
                                .build("/auction/LoginActivity")
                                .navigation(App.getApp());
                    } else if (code == 403) {
                        onError(jsonObject.optString("msg"));
                    } else if (code == -2) {//未设置资金密码
                        onError(jsonObject.optString("msg")+ ApiConstant.NO_PASS_TAIL);
                    } else if (code == -3){//未绑定身份
                        onError(jsonObject.optString("msg")+ ApiConstant.NO_AUTH_TAIL);
                    } else {
                        onError(jsonObject.optString("msg"));
                    }
                }
            } else {
                onCallBackError(new Throwable("-400", new Throwable("返回数据为空")));
            }
        } catch (Exception e) {
            onCallBackError(new Throwable("-500", new Throwable("网络开小差了")));
            e.printStackTrace();
        }
    }

    /**
     * 如有刷新操作可复写
     */
    protected void onStopRefresh() {

    }

    protected abstract void onError(String errorMsg);

    protected abstract void onSuccess(String dataJson);

    protected abstract void onCallBackError(Throwable e);

    @Override
    public void onError(Throwable e) {
       /* if (e != null && e.getMessage() != null && !e.getMessage().equals("")) {
            //onCallBackError(e);
            if (BuildConfig.DEBUG) {
                onCallBackError(new Throwable(e.getMessage()));
            } else {
                onCallBackError(new Throwable("网络开小差了"));
            }
        } else {
            if (BuildConfig.DEBUG) {
                onCallBackError(new Throwable("e is null"));
            } else {
                onCallBackError(new Throwable("网络开小差了"));
            }
        }*/
        onCallBackError(e);
    }

    @Override
    public void onComplete() {

    }
}
